/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.farmcode.core.runtime.event;


import com.farmcode.api.runtime.BaseEvent;
import com.farmcode.api.runtime.FARMCodeContext;
import com.farmcode.api.runtime.Response;
import java.io.File;
import java.io.FileFilter;

/**
 *
 * @author oiprado
 */
public class CleanEvent extends BaseEvent<String> {

    private FileFilter directoriesOnly = new FileFilter() {
        @Override
        public boolean accept(File file) {
            return file.isDirectory();
        }
    };
    private FileFilter filesOnly = new FileFilter() {
        @Override
        public boolean accept(File file) {
            return !file.isDirectory();
        }
    };

    
    @Override
    public Response<String> excecute(FARMCodeContext context) {
        try {
            String output = (String) context.get("output");
            File file = new File(output);
            clean(file);
            response.addMessage("Clean sucessfully");
        } catch (Exception ex) {
            response.addMessage(ex);
        }
        return response;
    }

    private void clean(File path) {
        File[] dirs = path.listFiles(directoriesOnly);
        if (dirs != null) {
            for (int i = 0; i < dirs.length; i++) {
                clean(dirs[i]);
                dirs[i].delete();
            }
        }

        File[] files = path.listFiles(filesOnly);
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                files[i].delete();
            }
        }
    }
}
